package com.msh.frame.common.util;

import lombok.extern.slf4j.Slf4j;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;

/**
 * @author shihu
 */
@Slf4j
public class IpUtil {


  /**
   * 不考虑格式错误，如果错误在程序中就会抛异常
   */
  public static int ipStringToInterger(String ip) {
    String[] strs = ip.split("\\.");
    int result = 0;
    for (int i = 0; i < 4; i++) {
      result = (result << 8) | (0xff & Integer.valueOf(strs[i]));
    }
    return result;
  }

  public static String ipIntegerToString(int ip) {
    StringBuilder stringBuilder = new StringBuilder();
    //负数时右移，第一位还是1
    stringBuilder.append((ip >> 24) & 0xff)
        .append(".")
        .append((ip >> 16) & 0xff)
        .append(".")
        .append((ip >> 8) & 0xff)
        .append(".")
        .append(ip & 0xff);
    return stringBuilder.toString();
  }

  public static void main(String[] args) {
    System.out.println(Integer.MIN_VALUE);
    int ip = ipStringToInterger("192.168.1.1");
    System.out.println(ip);
    System.out.println(ipIntegerToString(ip));
  }

  /**
   * 获取本地IP地址
   */
  public static String getLocalIP() {
    if (isWindowsOS()) {
      try {
        return InetAddress.getLocalHost().getHostAddress();
      } catch (UnknownHostException e) {
        log.error("get ip error", e);
      }
      return null;
    } else {
      return getLinuxLocalIp();
    }
  }

  public static boolean isWindowsOS() {
    boolean isWindowsOS = false;
    String osName = System.getProperty("os.name");
    if (osName.toLowerCase().indexOf("windows") > -1) {
      isWindowsOS = true;
    }
    return isWindowsOS;
  }

  /**
   * 获取Linux下的IP地址
   *
   * @return IP地址
   */
  private static String getLinuxLocalIp() {
    String ip = null;
    try {
      for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
          en.hasMoreElements(); ) {
        NetworkInterface intf = en.nextElement();
        String name = intf.getName();
        if (!name.contains("docker") && !name.contains("lo")) {
          for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses();
              enumIpAddr.hasMoreElements(); ) {
            InetAddress inetAddress = enumIpAddr.nextElement();
            if (!inetAddress.isLoopbackAddress()) {
              String ipaddress = inetAddress.getHostAddress().toString();
              if (!ipaddress.contains("::") && !ipaddress.contains("0:0:") && !ipaddress
                  .contains("fe80")) {
                ip = ipaddress;
              }
            }
          }
        }
      }
    } catch (SocketException ex) {
      log.error("get ip error", ex);
    }
    return ip;
  }
}
